package com.example.nacos.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    private final DiscoveryClient discoveryClient;

    private final RestTemplate restTemplate;
//    @Value("${providerName}")
    private final String providerName = "ComprehensiveProj";

    @Autowired
    public ConsumerController(DiscoveryClient discoveryClient, RestTemplate restTemplate) {
        this.discoveryClient = discoveryClient;
        this.restTemplate = restTemplate;
    }


    @GetMapping("/redis/get/{key}")
    public ResponseEntity<Object> redisGet(@PathVariable Object key){
        System.out.println(providerName);
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(providerName);
        ServiceInstance serviceInstance = serviceInstances.stream().findAny().orElseThrow(
                ()-> new IllegalStateException("no " + providerName + " instance available")
        );
        String uri = "http://"
                + serviceInstance.getHost() + ":"
                + serviceInstance.getPort()
                + "/redis/get/" + key;
        System.out.println(uri);
        return restTemplate.getForEntity(uri, Object.class);
    }

}
